package com.mazaiting.gateway.security;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.IoUtil;
import com.mazaiting.auth.constant.SecurityConst;
import com.mazaiting.common.core.domain.result.ResultCode;
import com.mazaiting.gateway.domain.SecureIgnoreBean;
import com.mazaiting.gateway.util.WebFluxUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.SecurityWebFiltersOrder;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
import org.springframework.security.oauth2.server.resource.authentication.ReactiveJwtAuthenticationConverterAdapter;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler;
import reactor.core.publisher.Mono;

import java.io.InputStream;
import java.security.KeyFactory;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 资源服务器配置
 */
@Slf4j
@Configuration
@EnableWebFluxSecurity
@RequiredArgsConstructor
public class ResourceServerConfig {
    /**
     * 资源服务器管理者
     */
    private final ResourceServerManager resourceServerManager;
    /**
     * 忽略的 URL
     */
    private final SecureIgnoreBean secureIgnoreBean;

    private final NoTokenAuthorizationFilter noTokenAuthorizationFilter;

    @Bean
    public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) throws Exception {
        List<String> urls = secureIgnoreBean.getUrls();
        if (Objects.isNull(urls)) {
            log.error("网关白名单路径读取失败：Nacos配置读取失败，请检查配置中心连接是否正确！");
            urls = new ArrayList<>();
        }

        http
                .oauth2ResourceServer()
                .jwt()
                .jwtAuthenticationConverter(jwtAuthenticationConverter())
//                .publicKey(rsaPublicKey())   // 本地加载公钥
                .jwkSetUri("http://127.0.0.1:9001/auth/v1/oauth/publicKey")  // 远程获取公钥，默认读取的key是spring.security.oauth2.resourceserver.jwt.jwk-set-uri
        ;
        http.oauth2ResourceServer()
                // 认证成功后没有权限操作
//                .accessDeniedHandler(new CustomServerAccessDeniedHandler())
                // 还没有认证时发生认证异常，比如token过期，token不合法
                .authenticationEntryPoint(authenticationEntryPoint())
        // 将一个字符串token转换成一个认证对象
//                .bearerTokenConverter(new ServerBearerTokenAuthenticationConverter())
        ;
        http.addFilterBefore(noTokenAuthorizationFilter, SecurityWebFiltersOrder.AUTHENTICATION);

        http.authorizeExchange()
                // 配置白名单
                .pathMatchers(Convert.toStrArray(urls)).permitAll()
                .anyExchange()
                .access(resourceServerManager)
                .and()
                .exceptionHandling()
                .accessDeniedHandler(accessDeniedHandler()) // 处理未授权
                .authenticationEntryPoint(authenticationEntryPoint()) // 处理未认证
                .and()
                .csrf().disable()
        ;

        return http.build();
    }

    /**
     * 自定义未授权响应
     */
    @Bean
    ServerAccessDeniedHandler accessDeniedHandler() {
        return (exchange, denied) -> {
            log.error("访问未授权");
            return Mono.defer(() -> Mono.just(exchange.getResponse()))
                    .flatMap(response -> WebFluxUtil.writeErrorInfo(response, ResultCode.ACCESS_UNAUTHORIZED));
        };
    }

    /**
     * token无效或者已过期自定义响应
     */
    @Bean
    ServerAuthenticationEntryPoint authenticationEntryPoint() {
        return (exchange, e) -> {
            log.error("token无效或已过期, 请重新登录");
            return Mono.defer(() -> Mono.just(exchange.getResponse()))
                    .flatMap(response -> WebFluxUtil.writeErrorInfo(response, ResultCode.TOKEN_INVALID_OR_EXPIRED));
        };
    }

    /**
     * @link <a href="https://blog.csdn.net/qq_24230139/article/details/105091273">...</a>
     * ServerHttpSecurity没有将jwt中authorities的负载部分当做Authentication
     * 需要把jwt的Claim中的authorities加入
     * 方案：重新定义权限管理器，默认转换器JwtGrantedAuthoritiesConverter
     */
    @Bean
    public Converter<Jwt, ? extends Mono<? extends AbstractAuthenticationToken>> jwtAuthenticationConverter() {
        JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
        jwtGrantedAuthoritiesConverter.setAuthorityPrefix(SecurityConst.AUTHORITY_PREFIX);
        jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName(SecurityConst.KEY_JWT_AUTHORITIES);
        JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
        jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwtGrantedAuthoritiesConverter);
        return new ReactiveJwtAuthenticationConverterAdapter(jwtAuthenticationConverter);
    }

    /**
     * 本地获取JWT验签公钥
     */
    @Bean
    public RSAPublicKey rsaPublicKey() throws Exception {
        org.springframework.core.io.Resource resource = new ClassPathResource("public.key");
        InputStream is = resource.getInputStream();
        String publicKeyData = IoUtil.read(is).toString();
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec((Base64.decode(publicKeyData)));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return (RSAPublicKey) keyFactory.generatePublic(keySpec);
    }

}
